package svalidator

import (
	ut "github.com/go-playground/universal-translator"
	"github.com/go-playground/validator/v10"
	"sgo/common/utils"
	"sgo/scontext"
)

type SgoValidator interface {
	validationFunc(fl validator.FieldLevel) bool
	registerFn(ut ut.Translator) error
	translationFn(ut ut.Translator, fe validator.FieldError) string
}

type UseWrapper struct {
	err error
}

func (uw *UseWrapper) wrapperFunc(ctx *scontext.SgoContext, validator SgoValidator, tag string) {
	if uw.err != nil {
		return
	}
	uw.err = use(ctx, validator, tag)
}

func Use(sc *scontext.SgoContext) error {

	// 统一处理错误
	useWrapper := &UseWrapper{}

	useWrapper.wrapperFunc(sc, PasswordValidator{}, "password_validator")

	// 在此处增加自定义校验
	// useWrapper.wrapperFunc(sc, PasswordValidator{}, "password_validator")

	if utils.IsNotNil(useWrapper.err) {
		return useWrapper.err
	}

	return nil
}

func use(sc *scontext.SgoContext, v SgoValidator, tag string) error {
	err := sc.Validator.Validate.RegisterValidation(tag, v.validationFunc)
	if err != nil {
		return err
	}
	// 注册自定义数据校验返回内容
	err = sc.Validator.Validate.RegisterTranslation(tag, *sc.Validator.Trans, v.registerFn, v.translationFn)
	if err != nil {
		return err
	}
	return nil
}
